<template>
  <div class="container">
    <!-- 账单信息 -->
    <div class="card2">
        <el-card>
            <div class="top">
                <div class="title1">账单信息</div>
                <div class="orderDetail">
                    <div>
                        <div>账单编号</div>
                        <div>老人姓名</div>
                        <div>账单金额（元）</div>
                        <div>账单周期</div>
                        <div>交易状态</div>
                        <div>创建人</div>
                    </div>
                    <div>
                        <div>{{ billData.billNo || '——' }}<span class="billType">{{ billData.billType}}</span></div>
                        <div>{{ billData?.elderly?.name }}</div>
                        <div>{{ formatAmount(billData.billAmount) || '——' }}</div>
                        <div>{{ formattedBillPeriod }}</div>
                        <div class="billStatus" :class="getTransactionStatusClass(billData.transactionStatus)">{{ getTransactionStatusText(billData.transactionStatus) || '——' }}</div>
                        <div>{{ billData.creatorUser?.nickName || billData.creatorUser?.userName || '——' }}</div>
                    </div>
                    <div>
                        <div>账单月份</div>
                        <div>老人身份证号</div>
                        <div>应付金额（元）</div>
                        <div>共计天数（天）</div>
                        <div>支付截止时间</div>
                        <div>创建时间</div>
                    </div>
                    <div>
                        <div>{{ billData.billMonth || '——' }}</div>
                        <div>{{ billData?.elderly?.idCard || '——' }}</div>
                        <div>{{ formatAmount(billData.payableAmount) || '——' }}</div>
                        <div>{{ billDays }}</div>
                        <div>{{ billData.paymentDeadline || '——' }}</div>
                        <div>{{ billData.createTime || '——' }}</div>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
    
    <!-- 账单明细 -->
    <div class="card1">
        <el-card>
            <div class="top">
                <div class="title1">账单明细</div>
                <div class="billDetailTable">
                    <table>
                        <thead>
                            <tr>
                                <th>类型</th>
                                <th>费用项目</th>
                                <th>服务内容</th>
                                <th class="text-right">金额（元）</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 添加项 -->
                            <template v-if="additionItems.length > 0">
                                <tr v-for="(item, index) in additionItems" :key="item.id || index">
                                    <td>{{ index === 0 ? '添加项' : '' }}</td>
                                    <td>{{ item.itemName }}</td>
                                    <td>{{ item.serviceContent || '——' }}</td>
                                    <td class="text-right">{{ formatAmount(item.amount) }}</td>
                                </tr>
                                <tr class="subtotal">
                                    <td colspan="2">小计</td>
                                    <td></td>
                                    <td class="text-right">{{ formatAmount(additionSubtotal) }}</td>
                                </tr>
                            </template>
                            
                            <!-- 扣除项 -->
                            <template v-if="deductionItems.length > 0">
                                <tr v-for="(item, index) in deductionItems" :key="item.id || index">
                                    <td>{{ index === 0 ? '扣减项' : '' }}</td>
                                    <td>{{ item.itemName }}</td>
                                    <td>{{ item.serviceContent || '——' }}</td>
                                    <td class="text-right">- {{ formatAmount(item.amount) }}</td>
                                </tr>
                                <tr class="subtotal">
                                    <td colspan="2">小计</td>
                                    <td></td>
                                    <td class="text-right">- {{ formatAmount(deductionSubtotal) }}</td>
                                </tr>
                            </template>
                            
                            <!-- 总计 -->
                            <tr>
                                <td colspan="2">每月应付</td>
                                <td></td>
                                <td class="text-right">{{ formatAmount(monthlyPayable) }}</td>
                            </tr>
                            <tr>
                                <td colspan="2">本期应付</td>
                                <td></td>
                                <td class="text-right">{{ formatAmount(billData.currentPayable) || '——' }}</td>
                            </tr>
                            <!-- <tr>
                                <td colspan="2">押金</td>
                                <td></td>
                                <td class="text-right">{{ formatAmount(billData.deposit) || '——' }}</td>
                            </tr> -->
                            <!-- <tr>
                                <td colspan="2">账单金额</td>
                                <td></td>
                                <td class="text-right">{{ formatAmount(billData.billAmount) || '——' }}</td>
                            </tr> -->
                            <!-- <tr>
                                <td colspan="2">预缴支付</td>
                                <td></td>
                                <td class="text-right">- {{ formatAmount(billData.prepaymentAmount) || '——' }}</td>
                            </tr> -->
                            <tr class="highlight">
                                <td colspan="2">应付金额</td>
                                <td></td>
                                <td class="text-right">{{ formatAmount(billData.payableAmount) || '——' }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </el-card>
    </div>
    
    <!-- 返回按钮 -->
    <div class="btn" @click="handleBack">返回</div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAccountEntryList } from '@/api/financialManagement/accountEntryList';

// 路由实例
const route = useRoute()
const router = useRouter()

// 从路由参数中获取id并转换为数字
const id = route.query.id ? Number(route.query.id) : null
console.log('账单ID:', id);

// 数据状态
const loading = ref(true)
const billData = ref({})
const billDetails = ref([])

// 计算属性：添加项列表
const additionItems = computed(() => {
  return billDetails.value.filter(item => item.type === '添加项')
})

// 计算属性：扣除项列表
const deductionItems = computed(() => {
  return billDetails.value.filter(item => item.type === '扣减项')
})

// 计算属性：添加项小计
const additionSubtotal = computed(() => {
  return additionItems.value.reduce((sum, item) => sum + (item.amount || 0), 0)
})

// 计算属性：扣除项小计
const deductionSubtotal = computed(() => {
  return deductionItems.value.reduce((sum, item) => sum + (item.amount || 0), 0)
})

// 计算属性：每月应付金额
const monthlyPayable = computed(() => {
  return additionSubtotal.value - deductionSubtotal.value
})

// 计算属性：计算账单周期天数
const billDays = computed(() => {
  if (!billData.value.billStartTime || !billData.value.billEndTime) {
    return '——'
  }
  const start = new Date(billData.value.billStartTime)
  const end = new Date(billData.value.billEndTime)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1 // 加1包含开始日期
  return diffDays
})

// 计算属性：格式化账单周期显示
const formattedBillPeriod = computed(() => {
  const start = billData.value.billStartTime || '——'
  const end = billData.value.billEndTime || '——'
  return start === '——' || end === '——' ? '——' : `${start} - ${end}`
})

/** 查询账单详情 */
function getBillAndBillDetails() {
  // 验证id是否有效
  if (!id || isNaN(id)) {
    console.error('无效的账单ID')
    loading.value = false
    return
  }
  
  loading.value = true
  getAccountEntryList(id).then(response => {
    billData.value = response.data || {}
    // 假设接口返回的账单明细数据在response.data.details中
    // 如果不是，请根据实际接口返回结构调整
    billDetails.value = response.data.billDetails || []
    // 如果接口没有返回明细数据，可以使用默认数据
    if (billDetails.value.length === 0) {
      // 使用您提供的JSON数据作为默认明细
      billDetails.value = [
        {
          "id": 0,
          "billId": 0,
          "type": "添加项",
          "itemName": "——",
          "serviceContent": "——",
          "amount": 0.00
        },
        {
          "id": 0,
          "billId": 0,
          "type": "扣除项",
          "itemName": "——",
          "serviceContent": "——",
          "amount": 0.00
        },
      ]
      console.log('使用默认明细数据')
    }
    
    loading.value = false
    console.log('账单数据:', billData.value)
    console.log('账单明细:', billDetails.value)
  }).catch(error => {
    console.error('获取账单详情失败:', error)
    loading.value = false
  })
}

/** 获取交易状态文本 */
function getTransactionStatusText(status) {
  const statusMap = {
    '0': '待支付',
    '1': '已支付',
    '2': '已关闭',
  }
  return statusMap[status] || '已支付'
}

/** 获取交易状态样式类 */
function getTransactionStatusClass(status) {
  const classMap = {
    '0': 'status-waiting',  // 待支付 - 黄色
    '1': 'status-paid',     // 已支付 - 绿色
    '2': 'status-closed'    // 已关闭 - 灰色
  }
  return classMap[status] || ''
}

/** 格式化金额 */
function formatAmount(amount) {
  if (amount === null || amount === undefined) {
    return '0.00'
  }
  return Number(amount).toFixed(2)
}

/** 返回上一页 */
function handleBack() {
  router.back()
}

// 页面加载时获取数据
onMounted(() => {
  getBillAndBillDetails()
})
</script>

<style scoped>
.container {
  margin: 15px;
  background-color: #FFFFFF;
  padding: 0px 0px 15px 10px;
}

.el-card {
  width: 100%;
  border-top: none;
  border-right: none;
}

.title1 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

/* 账单信息样式 */
.orderDetail {
  display: flex;
  margin-top: 20px;
}

.orderDetail > div > div {
  height: 50px;
  line-height: 50px;
}

.orderDetail > div:nth-child(1) > div,
.orderDetail > div:nth-child(3) > div {
  width: 120px;
}

.orderDetail > div:nth-child(2) > div {
  width: 240px;
}

.orderDetail > div:nth-child(1),
.orderDetail > div:nth-child(3) {
  text-align: right;
  color: #909399;
}

.orderDetail > div:nth-child(1) {
  margin-right: 50px;
  width: 100px;
}

.orderDetail > div:nth-child(2) {
  margin: 0 300px 0px 30px;
}

.orderDetail > div:nth-child(3) {
  margin-right: 60px;
}

/* 账单类型 */
.billType {
  font-size: 12px;
  color: #395ADA;
  border: 1px solid #395ADA;
  padding: 4px 5px;
  border-radius: 2px;
  margin-left: 10px;
}

/* 交易状态 */
.billStatus {
  display: inline-block;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
}

/* 待支付状态 - 黄色 */
.status-waiting {
  color: #f7ba1e;
}

/* 已支付状态 - 绿色 */
.status-paid {
  color: #67c23a;
}

/* 已关闭状态 - 灰色 */
.status-closed {
  color: #909399;
}

/* 账单明细表格样式 */
.billDetailTable {
  margin-top: 10px;
  width: 100%;
}

.billDetailTable table {
  width: 100%;
  border-collapse: collapse;
}

.billDetailTable th,
.billDetailTable td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #EBEEF5;
}

.billDetailTable th {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 500;
}

.billDetailTable td {
  color: #303133;
}

.billDetailTable .text-right {
  text-align: right;
}

/* 小计样式 */
.billDetailTable .subtotal {
  background-color: #F9FAFC;
  font-weight: bold;
}

/* 高亮行样式 */
.billDetailTable .highlight {
  background-color: #F2F6FC;
  font-weight: bold;
}

.billDetailTable .highlight td:last-child {
  color: #266FE8;
  font-size: 16px;
}

/* 卡片间距 */
.card1,
.card2 {
  margin-bottom: 20px;
}

.card2 {
  margin-top: 5px;
}

/* 按钮 */
.btn {
  width: 60px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #266FE8;
  color: #FFFFFF;
  border-radius: 5px;
  margin: 20px auto 52px;
  cursor: pointer;
}

.btn:hover {
  background-color: #4080FF;
}
</style>